package eleme.openapi.sdk.oauth.impl;

import java.io.IOException;

import eleme.openapi.sdk.config.Config;
import eleme.openapi.sdk.config.Constants;
import eleme.openapi.sdk.oauth.IOAuthClient;
import eleme.openapi.sdk.oauth.OAuthRequest;
import eleme.openapi.sdk.oauth.response.ErrorResponse;
import eleme.openapi.sdk.utils.JacksonUtils;
import eleme.openapi.sdk.utils.WebUtils;

/**
 * 客户端模式获取Token
 *
 * @author me
 */
public class DefaultOAuthClient implements IOAuthClient {

    /**
     * 默认连接超时时间为15秒
     */
    private static final int CONNECT_TIMEOUT = 15000;
    /**
     * 默认响应超时时间为30秒
     */
    private static final int READ_TIMEOUT = 30000;

    private String serverHostUrl;
    private Config context;

    public DefaultOAuthClient(Config context, String suffix) {
        this.context = context;
        this.serverHostUrl = context.getServerUrl() + suffix;
    }

    @Override
    public <T extends ErrorResponse> T execute(OAuthRequest<T> request) {
        try {
            String respJson = WebUtils.doPost(context, serverHostUrl,
                    request.getBodyMap(),
                    Constants.CHARSET_UTF8,
                    CONNECT_TIMEOUT,
                    READ_TIMEOUT,
                    request.getHeaderMap(),
                    WebUtils.getReqID()
            );
            // 构建响应解释器
            return JacksonUtils.json2obj(respJson, request.getResponseClass());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
